package com.xiao.train.business.controller;

import com.xiao.train.business.req.ConfirmOrderDoReq;
import com.xiao.train.business.service.BeforeConfirmOrderService;
import com.xiao.train.business.service.ConfirmOrderService;
import com.xiao.train.common.context.LoginMemberContext;
import com.xiao.train.common.resp.CommonResp;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("confirm-order")
public class ConfirmOrderController {

    @Autowired
    ConfirmOrderService confirmOrderService;

    @Autowired
    BeforeConfirmOrderService beforeConfirmOrderService;

    @Value("${spring.profiles.active}")
    String env;

    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping("do")
    public CommonResp doConfirm(@Valid @RequestBody ConfirmOrderDoReq req) {
        // 图形验证码校验
        if (!env.equals("dev")) {
            String imageCodeToken = req.getImageCodeToken();
            String imageCode = req.getImageCode();
            String imageCodeRedis = redisTemplate.opsForValue().get(imageCodeToken);
            log.info("从redis中获取到的验证码：{}", imageCodeRedis);
            if (ObjectUtils.isEmpty(imageCodeRedis)) {
                return new CommonResp(false, "验证码已过期", null);
            }
            // 验证码校验，大小写忽略，提升体验，比如Oo Vv Ww容易混
            if (!imageCodeRedis.equalsIgnoreCase(imageCode)) {
                return new CommonResp(false, "验证码不正确", null);
            } else {
                // 验证通过后，移除验证码
                redisTemplate.delete(imageCodeToken);
            }
        }
        req.setMemberId(LoginMemberContext.getId());
        Long orderId = beforeConfirmOrderService.beforeDoConfirm(req);
        return new CommonResp(orderId.toString());
    }

    @GetMapping("/query-line-count/{id}")
    public CommonResp queryLineCount(@PathVariable Long id) {
        Integer count = confirmOrderService.queryLineCount(id);
        return new CommonResp(count);
    }

    @GetMapping("/cancel/{id}")
    public CommonResp cancel(@PathVariable Long id) {
        Integer count = confirmOrderService.cancel(id);
        return new CommonResp(count);
    }
}